package adam2;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;

import javax.jmdns.JmDNS;
import javax.jmdns.ServiceInfo;
import javax.swing.JOptionPane;

public class Server implements Runnable {
	static String list;
	/**
	 * Accept this many connections.
	 */

	/**
	 * The server socket.
	 */
	private ServerSocket my_serverSocket;
	
	public static int port;

	/**
	 * Create the server socket.
	 * 
	 * @param a_port
	 *            the port that the server socket should listen on.
	 */
	public Server() {
		try {
			my_serverSocket = new ServerSocket(0);
			System.out.println(my_serverSocket.getLocalPort());
			port = my_serverSocket.getLocalPort();
		} catch (final IOException ioe) {
			ioe.printStackTrace();
		} catch (final SecurityException se) {
			se.printStackTrace();
		}
	}

	/**
	 * Method that listens on the server socket until close. Responds to to requests for files
	 *  and control commands
	 */

	@Override
	public void run() {
		while (true) {
			try {
				final long time = System.currentTimeMillis();
				final Socket socket = my_serverSocket.accept();
				final BufferedReader in = new BufferedReader(
						new InputStreamReader(socket.getInputStream()));
				final String line = in.readLine();
				final PrintWriter out = new PrintWriter(
						socket.getOutputStream(), true);
				String outLine = out.toString();
				if (line.equalsIgnoreCase("list")) {
					out.println(Walkin.walkin(new File(
							"C:\\media")));
				} else if (line.split("->")[0].equalsIgnoreCase("play")) {
					Thread streamServer = new Thread(new StreamingServer(5555));
					streamServer.start();
					System.out.println("playing: " + line.split("->")[1]);
					outLine = "playing->" + line.split("->")[1];
					System.out.println(outLine);
				} else if (line.split("->")[0].equalsIgnoreCase("command")) {
					outLine = "running command: " + line.split("->")[1];
				} else if(line.equals("stream")){
					Thread streamClient = new Thread(new StreamingClient("localhost", 5555));
					streamClient.start();
				} else {
					continue;
				}
				final long time2 = System.currentTimeMillis();
				final long timeTaken = time2 - time;
				System.out.println("Request processed in: " + timeTaken + "ms");
				out.println(outLine);
			} catch (final IOException ioe) {
				ioe.printStackTrace();
			} catch (final SecurityException se) {
				se.printStackTrace();
			}
		}
	}
	
	public static void main(String[] args) throws IOException {

		
		
		final JmDNS jmdns = JmDNS.create();


		// The TCPSocketServer class has been modified to run as a thread
		final Thread socket = new Thread(new Server());
		socket.start();
		String SERVICE_TYPE = null;
		String SERVICE_NAME = null;
		Object[] possibilities = {"media", "screen"};
		String s = (String)JOptionPane.showInputDialog(
		                    null,
		                    "Choose a device:\n",
		                    "Customized Dialog",
		                    JOptionPane.PLAIN_MESSAGE,
		                    null,
		                    possibilities,
		                    "ham");

		//If a string was returned, say so.
		if ((s != null) && (s.length() > 0)) {
			if(s.equals("media")){
				SERVICE_TYPE = "_media_service._tcp.local.";
				SERVICE_NAME = "media_"+port;
			}
			if(s.equals("screen")){
				SERVICE_TYPE = "_screen_service._tcp.local.";
				SERVICE_NAME = "screen_"+port;
			}
		}
		final ServiceInfo info = ServiceInfo.create(
				SERVICE_TYPE, SERVICE_NAME,
				port, 0, 0, "a_property=some_value");
		jmdns.registerService(info);
		System.out.println("Registered Service as " + info);
		// Wait for a keystroke before unregistering and quitting.

		System.out.println("Press enter to unregister and quit");
		new BufferedReader(new InputStreamReader(System.in)).readLine();
		// Unregister the service.
		jmdns.unregisterService(info);
		socket.stop();
		jmdns.close();
		System.exit(0);

	}
}
